const gravatar = require("gravatar");
const userService = require("../service/user.service");
const { getUserByCellphone, getUserByEmail, getUserByName } = require("../service/user.service");
const errorType = require("../constants/error-type");
const md5Password = require("../utils/password-md5");
const verifyUser = async (ctx, next) => {
  try {
    const { name, password, cellphone, email } = ctx.request.body;
    if (!name || !password || !cellphone || !email) {
      return ctx.app.emit("error", errorType.NAME_OR_EMAIL_OR_PHONE_IS_NOT_NULL, ctx);
    }
    const nameResult = await getUserByName(name);
    if (nameResult.length) {
      return ctx.app.emit("error", errorType.NAME_ALREADY_EXISTS, ctx);
    }
    const cellphoneResult = await getUserByCellphone(cellphone);

    if (cellphoneResult.length) {
      return ctx.app.emit("error", errorType.CELLPHONE_ALREADY_EXISTS, ctx);
    }
    const emailResult = await getUserByEmail(email);
    if (emailResult.length) {
      return ctx.app.emit("error", errorType.EMAIL_ALREADY_EXISTS, ctx);
    }
    await next();
  } catch (error) {
    console.log(error);
  }
};
// @ 密码
const handPassword = async (ctx, next) => {
  let { password } = ctx.request.body;
  ctx.request.body.pad = password;
  ctx.request.body.password = md5Password(password);
  await next();
};
const handleAvatar = async (ctx, next) => {
  const { email } = ctx.request.body;
  ctx.request.body.avatar = gravatar.url(email, { s: "200", r: "pg", d: "mm" });
  await next();
};
const getUserInfo = async (ctx, next) => {
  const { name } = ctx.request.body;
  const result = await userService.getUserByName(name);
  if (!result[0]) {
    return ctx.app.emit("error", errorType.USER_NAME_IS_NOT_EXISTS, ctx);
  }
  let user = {};
  for (const name in result[0]) {
    if (name === "password") continue;
    if (name === "pad") continue;
    user[name] = result[0][name];
  }
  ctx.user = user;
  await next();
};
module.exports = {
  verifyUser,
  handPassword,
  handleAvatar,
  getUserInfo
};
